import React from "react";
import { getLocale } from 'umi-plugin-react/locale';
import { Button, Layout } from "antd";
import Header from "@/layouts/Header";
import logo from "@/assets/logo.png";
import UserSession from "@/UserSession";
import robotDataClass from "./robotDataClass";
import styles from "./index.less";

const { Content, Sider } = Layout;

class Custom extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      userInfo: {},
      customUrl: null,
    }
  }

  componentDidMount(){
    const that = this;
    that.getApplicationId()
    window.addEventListener('message', function (event) {
      if (event.data === "done") {
        //接收到子页面传来的信息-表示子页面加载完成-父页面可以进行传值
        that.postMessageToCustom()
      }
    });
  }

  getApplicationId = () => {
    robotDataClass.getApplicationId({}, res => {
      if (res.data.code === 0) {
        const { applicationId } = res.data.data;
        const currentUser = UserSession.getCurrentUser();
        const appId = currentUser.isAdmin ? currentUser.applicationId : applicationId;
        const username = currentUser.username;
        this.setState({ userInfo: res.data.data });
        robotDataClass.initSSO(appId, username).then(response => {
          if (response.data.code === 0 && response.data.data) {
            this.setState({
              customUrl: `/custom/login?applicationId=${appId}&code=${response.data.data}&lang=${getLocale()}`
            });
          }
        });
      }
    })
  }

  postMessageToCustom = () => {
    const { location:{param} } = this.props;
    if(param && param.chat_question != '' && param.chat_question != null && param.chat_question != undefined){
      const iframe = document.getElementById('custom')
      iframe.contentWindow.postMessage('parentMessage-'+param.chat_question, "*");
    }
  }

  render(){
    const { customUrl } = this.state;
    return (
      <div>
        <Layout style={{minHeight:"100vh"}}>
          <Header logo={logo} isHome={true} />
          <Content className={styles.content}>
            { customUrl && <iframe id="custom" key={new Date().getTime()} src={customUrl} style={{width:'100%',height:"calc(100vh - 70px)",marginTop:65,border:'none'}} /> }
          </Content>
        </Layout>
      </div>
    )
  }
}

export default Custom
